import Vue from "vue"
import Router from "vue-router"
import store from "@/store"
import adminMenu from "@/assets/menus/adminMenu"
import * as utils from "@/utils/comm"
import common from "@/router/modules/common"

Vue.use(Router)

// window.onbeforeunload = onbeforeunload_handler
//    function onbeforeunload_handler(){
//        var warning="确认退出1111111?"
//        console.log(11111111111111111)
//        return warning
// }

const router = new Router({
  mode: "history",
  routes: [{
    path: "/",
    redirect: "/index"
  },
  {
    path: "/index",
    name: "首页",
    component: () =>
        import("@/views/index/index")
  },
  ...common
  ]
})

let titleTpl = " | 后台管理"

router.beforeEach((to, from, next) => {
  let breadCrumbArray = [];
  let bcObj = {};
  let bcLists = utils.checkMenuToBreadCrumb(adminMenu, to.path, breadCrumbArray, bcObj)
  store.commit("SET_BREADCRUMB_LIST", bcLists.breadCrumbList)
  let checkMenu = bcLists.breadCrumbList.slice(bcLists.breadCrumbList.length - 1, bcLists.breadCrumbList.length)[0]

  if (checkMenu !== undefined) {
    store.commit("ADD_TABS_VIEWS", checkMenu)
    store.commit("TAB_ACTIVE_NAME", checkMenu.path)
  } else {
    store.commit("TABS_VIEWS", [])
    store.commit("TAB_ACTIVE_NAME", "")
  }
  if (to.path === "/login") {
    document.title = `登录${titleTpl}`
  } else if (to.path === "/401") {
    document.title = `401${titleTpl}`
  } else if (to.path === "/404") {
    document.title = `404${titleTpl}`
  } else {
    document.title = `${to.name}${titleTpl}`
  }
  let role = localStorage.getItem("role")
  let urole = to.meta && to.meta.role
  if ((role && (role === urole)) || (to.path === "/login") || !urole) {
    next()
  } else {
    alert("没有权限")
    next(false)
  }
})

export default router
